package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.core.utils.sign.Base64;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.domain.SysUserRole;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.IFileService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private IFileService fileService;

    @Autowired
    private RemoteFileService remoteFileService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        if (user.getOrgId() == null) {
            Long orgId = SecurityUtils.getLoginUser().getSysUser().getOrgId();
            user.setOrgId(orgId);
        }
        return userMapper.selectUserList(user);
    }

    /**
     * 查询用户树状列表
     *
     * @param sysUser
     * @return
     */
    public List<SysUser> selectTreeUser(SysUser sysUser) {
        List<SysUser> sysUserList = userMapper.selectTreeUser(sysUser);
        List<Long> deptIds = sysUserList.stream().map(SysUser::getParentId).distinct().collect(Collectors.toList());
        sysUser.setDeptIds(deptIds);
        List<SysUser> sysDeptList = userMapper.selectDeptList(sysUser);
        sysUserList.addAll(sysDeptList);
        return sysUserList;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectLoginUserByUserName(String userName, Long orgId, String orgName) {
        return userMapper.selectLoginUserByUserName(userName, orgId, orgName);
    }

    @Override
    public Integer[] selectUserGroupIds(Long userId) {
        List<Integer> userGroupIdLIst = jdbcTemplate.queryForList("select group_id from sys_user_group where user_id=?", Integer.class, userId);
        if (userGroupIdLIst.size() > 0)
            return userGroupIdLIst.toArray(new Integer[userGroupIdLIst.size()]);
        return null;
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        SysUser user = userMapper.selectUserById(userId);
        List<Integer> userGroupIdLIst = jdbcTemplate.queryForList("select group_id from sys_user_group where user_id=?", Integer.class, userId);
        if (userGroupIdLIst.size() > 0)
            user.setGroupIds(userGroupIdLIst.toArray(new Integer[userGroupIdLIst.size()]));
        // List<SysUserEdu> sysUserEduList = jdbcTemplate.query("select * from sys_user_edu where user_id=?", new BeanPropertyRowMapper<>(SysUserEdu.class), userId);
        // if (StringUtils.isNotEmpty(sysUserEduList)) {
        //     user.setUserEduList(sysUserEduList);
        // }
        // List<SysUserWork> sysUserWorkList = jdbcTemplate.query("select * from sys_user_work where user_id=?", new BeanPropertyRowMapper<>(SysUserWork.class), userId);
        // if (StringUtils.isNotEmpty(sysUserWorkList)) {
        //     user.setUserWorkList(sysUserWorkList);
        // }
        return user;
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(SysUser user) {
        Long userId = user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info)) {
            if (userId == null) {
                return UserConstants.NOT_UNIQUE;
            } else if (info.getUserId().longValue() != userId.longValue()) {
                return UserConstants.NOT_UNIQUE;
            }
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId, Long orgId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            Long orgId1 = SecurityUtils.getOrgId();
            if (orgId1 == 0 && orgId != null) {
                user.setOrgId(orgId);
            }
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertUser(SysUser user) {
        //姓名去除空格
        String nickName = user.getNickName().replace(" ", "");
        user.setNickName(nickName);
        // 新增用户信息
        if (user.getUserId() == null) {
            user.setUserId(Seq.getSeqId());
        }
        checkUserAllowed(user);
        //获取默认密码
        String password = configService.selectConfigByKey("sys.user.initPassword");
        if (StringUtils.isNull(password)) {
            throw new ServiceException("获取默认密码失败");
        }
        user.setPassword(SecurityUtils.encryptPassword(password));
        user.setPassword(SecurityUtils.encryptPassword(password));
        int row = userMapper.insertUser(user);
        // insertUserEdu(user);
        // insertUserWork(user);
        // Long userId = jdbcTemplate.queryForObject("select max(user_id) count from sys_user where org_id=?",Long.class,user.getOrgId());
        // if (userId!=null){
        //     return userId;
        // }
        // return null;
        return user.getUserId();
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        if (user.getUserId() == null) {
            user.setUserId(Seq.getSeqId());
        }
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(SysUser user) {

        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        insertUserGroup(user);
        // insertUserEdu(user);
        // insertUserWork(user);
        //姓名去除空格
        String nickName = user.getNickName().replace(" ", "");
        user.setNickName(nickName);
        int row = userMapper.updateUser(user);
        return row;
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        SysUser user = new SysUser();
        user.setRoleIds(roleIds);
        user.setUserId(userId);
        insertUserRole(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(long userId, long avatar) {
        return userMapper.updateUserAvatar(userId, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param sysUser 用户对象
     */
    public void insertUserRole(SysUser sysUser) {
        if (StringUtils.isNotEmpty(sysUser.getRoleIds())) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : sysUser.getRoleIds()) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(sysUser.getUserId());
                ur.setRoleId(roleId);
                if (sysUser.getOrgId() == null)
                    ur.setOrgId(SecurityUtils.getOrgId());
                else//来源于机构管理
                    ur.setOrgId(sysUser.getOrgId());
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 新增用户组信息
     *
     * @param user 用户对象
     */
    public void insertUserGroup(SysUser user) {
        jdbcTemplate.update("delete from sys_user_group where user_id=?", user.getUserId());
        Integer[] groupIds = user.getGroupIds();
        if (StringUtils.isNotEmpty(groupIds)) {
            jdbcTemplate.batchUpdate("insert into sys_user_group(user_id,group_id,org_id) values (?,?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setLong(1, user.getUserId());
                    ps.setInt(2, groupIds[i]);
                    ps.setLong(3, SecurityUtils.getOrgId());
                }

                @Override
                public int getBatchSize() {
                    return groupIds.length;
                }
            });
        }
    }

    /**
     * 新增用户教育经历信息
     *
     * @param user 用户对象
     */
    public void insertUserEdu(SysUser user) {
        jdbcTemplate.update("delete from sys_user_edu where user_id=?", user.getUserId());
        List<SysUserEdu> userEduList = user.getUserEduList();
        if (StringUtils.isNotEmpty(userEduList)) {
            jdbcTemplate.batchUpdate("insert into sys_user_edu(edu_id,user_id,school,xl,xw,zy,start_date,end_date) values (?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setLong(1, userEduList.get(i).getEduId());
                    ps.setLong(2, user.getUserId());
                    ps.setString(3, userEduList.get(i).getSchool());
                    ps.setInt(4, userEduList.get(i).getXl());
                    ps.setInt(5, userEduList.get(i).getXw());
                    ps.setString(6, userEduList.get(i).getZy());
                    ps.setDate(7, userEduList.get(i).getStartDate());
                    ps.setDate(8, userEduList.get(i).getEndDate());
                }

                @Override
                public int getBatchSize() {
                    return userEduList.size();
                }
            });
        }
    }

    /**
     * 新增用户教育经历信息
     *
     * @param user 用户对象
     */
    public void insertUserWork(SysUser user) {
        jdbcTemplate.update("delete from sys_user_work where user_id=?", user.getUserId());
        List<SysUserWork> userWorkList = user.getUserWorkList();
        if (StringUtils.isNotEmpty(userWorkList)) {
            jdbcTemplate.batchUpdate("insert into sys_user_work(work_id,user_id,work_name,zw,zc,start_date,end_date) values (?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setLong(1, userWorkList.get(i).getWorkId());
                    ps.setLong(2, user.getUserId());
                    ps.setString(3, userWorkList.get(i).getWorkName());
                    ps.setString(4, userWorkList.get(i).getZw());
                    ps.setInt(5, userWorkList.get(i).getZc());
                    ps.setDate(6, userWorkList.get(i).getStartDate());
                    ps.setDate(7, userWorkList.get(i).getEndDate());
                }

                @Override
                public int getBatchSize() {
                    return userWorkList.size();
                }
            });
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId, null);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        int row = userMapper.deleteUserByIds(userIds);
        return row;
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(user);
                    checkUserDataScope(user.getUserId(), null);
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String getRandomMySign(Long userId) {
        File file = new File();
        if (userId == null) {
            userId = SecurityUtils.getUserId();
        }
        file.setGroupId(userId);
        file.setTypeId(21);
        List<File> fileList = fileService.selectFileList(file);
        if (fileList.size() == 0) return null;
        if (fileList.size() == 1) file = fileList.get(0);
        int randomIndex = (int) (Math.random() * fileList.size());
        file = fileList.get(randomIndex);
        R<byte[]> fileResult = remoteFileService.download("", file.getFilePath());
        if (fileResult.getCode() == 200) {
            byte[] fileData = fileResult.getData();
            return Base64.encode(fileData);
        } else if (fileList.size() > 1) {//根据当前图片id在文件服务器未查询到图片，尝试读取其它图片
            int i = 0;
            for (File tempFile : fileList) {
                if (i == randomIndex) continue;//排除掉随机图片索引因为在上面if中已经读取过了。
                fileResult = remoteFileService.download("", tempFile.getFilePath());
                if (fileResult.getCode() == 200) {
                    byte[] fileData = fileResult.getData();
                    return Base64.encode(fileData);
                }
                i++;
            }
        }
        return null;
    }

    @Override
    public List<SysUser> selectUserRoleList(SysUser user) {
        return userMapper.selectUserRoleList(user);
    }

    @Override
    public SysUser selectUserInfoByUserId(Long userId) {
        return userMapper.selectUserInfoByUserId(userId);
    }

    @Override
    public List<Map<String, Object>> selectSimpleUserList(SysUser user) {
        List<SysUser> sysUserList = userMapper.selectSimpleUserList(user);
        return groupByFirstLetter(sysUserList);
    }

    @Override
    public Long getUserId(String nickName) {
        return userMapper.getUserId(nickName);
    }

    @Override
    public String checkUserName(SysUser user) {
        SysUser user1 = userMapper.selectUserByUserNameAll(user);
        if (user1 == null) {
            return UserConstants.UNIQUE;
        }
        return UserConstants.NOT_UNIQUE;
    }

    @Override
    public Boolean isValidPhoneNumber(String userName) {
        String CHINA_PHONE_NUMBER_REGEX = "^1[3-9]\\d{9}$";
        if (userName == null) {
            return false;
        }
        return userName.matches(CHINA_PHONE_NUMBER_REGEX);
    }

    public List<Map<String, Object>> groupByFirstLetter(List<SysUser> sysUserList) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<Character, List<String>> groupedMap = new HashMap<>();
        for (SysUser sysUser : sysUserList) {
            char firstLetter = sysUser.getUserName().toUpperCase(Locale.ROOT).charAt(0);
            groupedMap.computeIfAbsent(firstLetter, k -> new ArrayList<>()).add(sysUser.getNickName());
        }
        groupedMap.forEach((letter, data) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("letter", letter);
            map.put("data", data);
            list.add(map);
        });
        return list;
    }
}
